package com.example.java_gobang.api;


import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
//@RequestMapping("/user")
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @ResponseBody
    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        //关键操作: 根据username去数据库中进行查询
        //如果能匹配的用户,并且密码一致,就认为登录成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username="+username);
        if(user == null || !user.getPassword().equals(password)){
            //登录失败
            System.out.println("登陆失败");
            return new User();
        }
        HttpSession httpSession = req.getSession(true);//如果不存在会话,则自动创建一个会话
        httpSession.setAttribute("user", user);//将用户信息放到会话里
        return user;
    }

    @ResponseBody
    @PostMapping("/register")
    public Object register(String username, String password){

        try {
            User user = new User();
            user.setUsername(username);//其他值在userMapper插入操作时就设置了
            user.setPassword(password);
            userMapper.insert(user);
            return user;
            //用户名相同的异常
        } catch (org.springframework.dao.DuplicateKeyException e) {
            User user = new User();//注册失败,返回一个空对象
            return user;
        }
    }

    @ResponseBody
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req){
        try {
            HttpSession httpSession = req.getSession(false);
            User user = (User)httpSession.getAttribute("user");//login接口返回的是Object类型,要强转
            //拿着这个 user 对象, 去数据库找最新的数据
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            return new User();
        }
    }
}
